<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>防刷限流配置</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="/lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="/css/public.css" media="all">
<style>
/* 防止下拉框的下拉列表被隐藏*/

.layui-table-cell { overflow: visible !important; }

.layui-table-box {
    overflow: visible;
}
        
.layui-table-body {
    overflow: visible;
}

/* 使得下拉框与单元格刚好合适 */
td .layui-form-select{
    margin-top: -10px;
    margin-left: -15px;
    margin-right: -15px;
}
</style>
</head>
<body>
<div class="layuimini-container">
    <div class="layuimini-main">
        <blockquote class="layui-elem-quote layui-text">
            限流规则文档说明:1. <a href="#" target="_blank">限流规则添加帮助文档</a> 
            <a class="layui-btn" style="float:right" href="javascript:location.replace(location.href);" title="刷新">
              <i class="layui-icon">&#xe669;</i></a>
        </blockquote>
            <fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
                <legend><div id="appNameTitle"></div>全局配置项</legend>
            </fieldset>  
              <form class="layui-form layui-form-pane"  action="" lay-filter="UpdateInfo">
                <div class="layui-form-item" pane="">
                    <label class="layui-form-label">防刷状态</label>
                        <div class="layui-input-block">
                            <input type="radio" name="reqlimit_enable" value="record"  lay-filter="reqlimitEnable" title="只记录不限制" checked="">
                            <input type="radio" name="reqlimit_enable" value="on" lay-filter="reqlimitEnable" title="开启">
                            <input type="radio" name="reqlimit_enable" value="off" lay-filter="reqlimitEnable" title="关闭">                                                                            
                        </div>  
                </div>  
                <div class="layui-form-item" pane="">
                    <label class="layui-form-label">内网请求<i class="layui-icon layui-icon-about intranet-marks" style="color: #1E9FFF;"></i></label>
                    <div class="layui-input-block">
                        <input type="checkbox" name="reqlimit_exclude_intranet" lay-skin="switch" lay-filter="switchTest" lay-text="排除|不排除">                                                 
                    </div>
                </div>

                <div class="layui-form-item" pane="">
                    <label class="layui-form-label">静态文件<i class="layui-icon layui-icon-about static-marks" style="color: #1E9FFF;"></i></label>
                    <div class="layui-input-block">    
                        <input type="checkbox" name="reqlimit_exclude_static" lay-skin="switch" lay-filter="switchTest" lay-text="排除|不排除">                                              
                    </div>                 
                </div> 
  
                <div class="layui-form-item" pane="">
                    <label class="layui-form-label">白名单</label>
                    <div class="layui-input-inline">    
                        <input type="checkbox" name="reqlimit_white_enable" lay-skin="switch" lay-filter="switchTest" lay-text="ON|OFF">                                              
                    </div> 
                    <div class="layui-input-inline" style="width:150px">  
                        <button class="layui-btn layui-btn-primary layui-border-green" id="whiteListBtn" style="width:150px" type="button">白名单管理</button>
                    </div>                
                </div>  

                <div class="layui-form-item" pane="">
                    <label class="layui-form-label">cookie<i class="layui-icon layui-icon-about cookie-marks" style="color: #1E9FFF;"></i></label>
                    <div class="layui-input-inline">    
                        <input type="checkbox" name="reqlimit_exclude_pcsuv" lay-skin="switch" lay-filter="switchTest" lay-text="排除|不排除">                                              
                    </div>   
                    <div class="layui-form-mid layui-word-aux">在高级配置项里设置需要排除的cookie</div>                 
                </div>

                <div class="layui-form-item" pane="">
                    <label class="layui-form-label">子请求<i class="layui-icon layui-icon-about subRequest-marks" style="color: #1E9FFF;"></i></label>
                    <div class="layui-input-block">
                        <input type="checkbox" name="reqlimit_exclude_subrequest" lay-skin="switch" lay-filter="switchTest" lay-text="排除|不排除">                                                 
                    </div>
                </div>

                <div class="layui-form-item" pane="">
                    <label class="layui-form-label">内部请求<i class="layui-icon layui-icon-about internalRequest-marks" style="color: #1E9FFF;"></i></label>
                    <div class="layui-input-block">
                        <input type="checkbox" name="reqlimit_exclude_internalrequest" lay-skin="switch" lay-filter="switchTest" lay-text="排除|不排除">                                                 
                    </div>
                </div>
              </form>

            <fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
                <legend>限流规则配置</legend>
            </fieldset>
        <table class="layui-table" id="currentTableId" lay-filter="currentTableFilter"></table>
        <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container">
                <button class="layui-btn" lay-event="add"> 添加 </button>
            </div>
        </script>
        <script type="text/html" id="currentTableBar">
            <!-- <a class="layui-btn layui-btn-xs layui-btn-warm" lay-event="edit">更改限流策略</a> -->
            <a class="layui-btn layui-btn-xs layui-btn-danger data-count-delete" lay-event="delete">删除</a>
        </script>

    </div>
</div>
<script src="/lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
<script type="text/html" id="limitKeyTpl">
  <div style="overflow:hidden;white-space:nowrap;text-overflow:ellipsis;">{{d.limit_key}}</div>
</script>
<script type="text/html" id="limitEnableTpl">
  <input type="checkbox" name="limit_enable" value="{{d.id}}" lay-skin="switch" lay-text="启用|停用" lay-filter="limitEnable" {{ d.limit_enable == true ? 'checked' : '' }}>
</script>
<script type="text/html" id="limitSpeedTpl">
  <input type="checkbox" name="limit_speed" value="{{d.id}}" lay-skin="switch" lay-text="限速|不限" lay-filter="limitEnable" {{ d.limit_speed == true ? 'checked' : '' }}>
</script>
<script type="text/html" id="limitTypeTpl">
  <select id="{{d.id}}" name="limit_type" class="layui-border"  lay-filter="limitType">
		<option value="ip" {{ d.limit_type == 'ip' ? 'selected' : '' }}>IP</option>
		<option value="cip" {{ d.limit_type == 'cip' ? 'selected' : '' }}>C段IP</option>
		<option value="ipuri" {{ d.limit_type == 'ipuri' ? 'selected' : '' }}>单IP单URI</option>
		<option value="useragent" {{ d.limit_type == 'useragent' ? 'selected' : '' }}>UserAgent</option>
		<option value="referer" {{ d.limit_type == 'referer' ? 'selected' : '' }}>Referer</option>
		<option value="args" {{ d.limit_type == 'args' ? 'selected' : '' }}>Args</option>
		<option value="all" {{ d.limit_type == 'all' ? 'selected' : '' }}>ALL</option>
  </select>
</script>
<script>

    function getQueryString(name) {
      let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
      let r = window.location.search.substr(1).match(reg);
      if (r != null) {
          return unescape(r[2]);
      };
      return null;
    };

    layui.use(['form', 'table'], function () {
        var $ = layui.jquery,
            form = layui.form,
            table = layui.table;

var htmls = getQueryString("appname");
$('#appNameTitle').html(htmls);

			$.ajax({
			   url: "/xwaf/config/v1/GetReqlimitConfig" + location.search,
			   type: "GET",
			   headers:{'X-Requested-With':'XMLHttpRequest'},
			   success: function (resp) {          
					if (resp.id > 0 ) {
      				  form.val('UpdateInfo', {
                  "id": resp.id
                  ,"appname": resp.appname
                  ,"reqlimit_enable": resp.reqlimit_enable
                  ,"reqlimit_exclude_intranet": resp.reqlimit_exclude_intranet
                  ,"reqlimit_exclude_static": resp.reqlimit_exclude_static
                  ,"reqlimit_exclude_pcsuv": resp.reqlimit_exclude_pcsuv
                  ,"reqlimit_exclude_subrequest": resp.reqlimit_exclude_subrequest
                  ,"reqlimit_exclude_internalrequest": resp.reqlimit_exclude_internalrequest
                  ,"reqlimit_white_enable": resp.reqlimit_white_enable
                  ,"reqlimit_statuscode": resp.reqlimit_statuscode
                  ,"limit_html": resp.limit_html
                  ,"updatetime": resp.updatetime                              
      				  }) 
            }else{
              layer.msg(resp.msg,{icon:2});
            }
				  }
		    });	

        $('#whiteListBtn').on("click",function(){
                layer.open({
                    title: '白名单管理',
                    type: 2,
                    shade: 0.2,
                    maxmin:true,
                    shadeClose: true,
                    area: ['50%', '80%'],
                    content: '/page/xwaf/reqlimit_white_list.html'+ location.search,
                });
        });

$(".static-marks").mouseover(function() {
    layer.tips('静态文件忽略不做任何操作,直接放行!', this, {
      tips: [1, "#000"],
      time:3000
    });
});

$(".intranet-marks").mouseover(function() {
    layer.tips('从内网IP过来的请求不做任何操作,直接放行!', this, {
      tips: [1, "#000"],
      time:3000
    });
});

$(".cookie-marks").mouseover(function() {
    layer.tips('设置特定的cookie，判断带有此cookie,直接放行!', this, {
      tips: [1, "#000"],
      time:3000
    });
});

$(".subRequest-marks").mouseover(function() {
    layer.tips('nginx的ssi之类的请求!', this, {
      tips: [1, "#000"],
      time:3000
    });
});

$(".internalRequest-marks").mouseover(function() {
    layer.tips('nginx内部的rewrite、404重试之类的请求!', this, {
      tips: [1, "#000"],
      time:3000
    });
});

//修改各个check状态
  form.on('switch(switchTest)', function(data){
    //layer.msg('开关checked：'+ (this.checked ? 'true' : 'false'), {
    //  offset: '6px'
    //});
    //console.log(this.checked);
    //console.log(this.name);
    //console.log(this.value);
    var bodystr = {"name":this.name,"value":this.checked};
    //console.log(JSON.stringify(bodystr))
			$.ajax({
			   url: "/xwaf/config/v1/EditWafConfig" + location.search,
			   type: "GET",
			   headers:{'X-Requested-With':'XMLHttpRequest'},
         type: "post",
         data: JSON.stringify(bodystr),
         dataType: "json",
			   success: function (resp) {
					  if (resp.code == 0 ) {
              layer.msg('更改成功', {icon: 1});
            }else{
              layer.msg(resp.msg,{icon:2});
            }
				  }
		    });
        //layer.tips('温馨提示：请注意开关状态的文字可以随意定义，而不仅仅是ON|OFF', data.othis)
  });

//限流状态改变
  form.on('radio(reqlimitEnable)', function(data){
    //console.log(this.name);
    //console.log(this.value);
    var bodystr = {"name":this.name,"value":data.value};
			$.ajax({
			   url: "/xwaf/config/v1/EditWafConfig" + location.search,
			   type: "GET",
			   headers:{'X-Requested-With':'XMLHttpRequest'},
         type: "post",
         data: JSON.stringify(bodystr),
         dataType: "json",
			   success: function (resp) {
					  if (resp.code == 0 ) {
              layer.msg('更改成功', {icon: 1});
            }else{
              layer.msg(resp.msg,{icon:2});
            }
				  }
		    });
  });

        table.render({
            elem: '#currentTableId',
            url: '/xwaf/reqlimit/rule/List' + location.search,
            toolbar: '#toolbarDemo',
            //editTrigger: 'dblclick',
            defaultToolbar: ['filter'],
            cols: [[
                //{type: "checkbox", width: 50},
                {field: 'id',width:60,  title: 'ID'},
                {field: 'appname', title: '应用名', hide:true},
                {field: 'limit_host', title: '域名', edit:true},
                {field: 'limit_url', title: 'URL', edit:true},      
                {field: 'limit_type',title: '限流类型', templet: '#limitTypeTpl'},                          
                {field: 'limit_key',title: '关键字', edit:true, sort: true,templet:'#limitKeyTpl'},
                {field: 'limit_rate',width:150,title:'阀值[qps]<i class="layui-icon layui-icon-about rate-marks" style="color: #1E9FFF;"></i>', edit:true},
                {field: 'limit_speed',width:120,title:'限速<i class="layui-icon layui-icon-about speed-marks" style="color: #1E9FFF;"></i>', templet: '#limitSpeedTpl'},
                {field: 'limit_enable',width:120,title:'状态',sort: true,templet: '#limitEnableTpl'},  
                {field: 'limit_priority',title:'优先级',edit:true,sort: true,hide:true},       
                {field: 'limit_downrate',title:'速度[KB/s]<i class="layui-icon layui-icon-about downrate-marks" style="color: #1E9FFF;"></i>',edit:true,sort: true},          
                {field: 'remarks',title:'备注',edit:'text', sort: true},
                {field: 'createtime', title: '创建时间', hide:true},
                {field: 'updatetime', title: '更新时间', hide:true},
                {title: '操作', minWidth:130, toolbar: '#currentTableBar', align: "center"}
            ]],
            limits: [25, 50, 100],
            limit: 15,
            page: true,
            done(){
            	$(".rate-marks").mouseover(function() {
                layer.tips('阀值可以是整数或小数，小数时保留3位小数。例如：为0.2时，表示5秒钟一个请求!', this, {
                  tips: [1, "#000"],
                  time:2000
                });
              });

            	$(".speed-marks").mouseover(function() {
                layer.tips('开启时,限制超出请求的响应时间!', this, {
                  tips: [1, "#000"],
                  time:2000
                });
              });

            	$(".downrate-marks").mouseover(function() {
                layer.tips('限制网页的下载速度!', this, {
                  tips: [1, "#000"],
                  time:2000
                });
              });
            }
        });
        
      //table里状态
      form.on('switch(limitEnable)', function(data){
        var bodystr = {"name":this.name,"value":this.checked};
    			  $.ajax({
    			   url: "/xwaf/reqlimit/rule/Edit" + location.search+"&id="+this.value,
    			   headers:{'X-Requested-With':'XMLHttpRequest'},
             type: "POST",
             data: JSON.stringify(bodystr),
             dataType: "json",
    			   success: function (resp) {
    					  if (resp.code == 0 ) {
                  layer.msg('更改成功', {icon: 1});
                }else{
                  layer.msg(resp.msg,{icon:2});
                }
    				  }
    		    });
      });

      //table 里下拉框
      form.on('select(limitType)', function(data){
        var bodystr = {"name":data.elem.name,"value":data.value};
        console.log(data);
        var elem = $(data.elem);
        var trElem = elem.parents('tr');
        var tableData = table.cache['grid'];
            // 更新到表格的缓存数据中，才能在获得选中行等等其他的方法中得到更新之后的值
        console.log(data.elem.id);
        console.log(bodystr);
        //tableData[trElem.data('index')][elem.attr('name')] = data.value;
        layer.confirm('确定修改?', {icon: 3, title:'提示',yes: function(index){
    			  $.ajax({
    			   url: "/xwaf/reqlimit/rule/Edit" + location.search+"&id="+data.elem.id,
    			   type: "POST",
    			   headers:{'X-Requested-With':'XMLHttpRequest'},
             data: JSON.stringify(bodystr),
             dataType: "json",
    			   success: function (resp) {
    					  if (resp.code == 0 ) {
                  layer.msg('更改成功', {icon: 1});
                }else{
                  layer.msg(resp.msg,{icon:2});
                }
    				  }
    		    });
          },
          cancel: function(index, layero){ 
                layer.close(index);
          } 
        });  
      });
  
  	//监听表格编辑
  	table.on('edit(currentTableFilter)', function(obj){
    	var value = obj.value //得到修改后的值
    	,datas = obj.data //得到所在行所有键值
    	,field = obj.field; //得到字段
      if (field == "limit_rate") {
          //var re = /^\d+\/\d+$/;
          var re = /^\d*\.?\d+$/;
          if (!re.test(value)){
              layer.msg("必须为大于0的整数或小数!",{icon:2});
              return false;
          } 
      }     

      value = value.replace(/^\s*|\s*$/g,"");
      //console.log(value);
      var bodystr = {"appname":datas.appname,"name":field,"value":value};
        layer.confirm('确定修改?', {icon: 3, title:'提示',yes: function(index){      
           	$.ajax({
               	url: "/xwaf/reqlimit/rule/Edit"+ location.search+"&id="+datas.id,
                type: "POST",
                data: JSON.stringify(bodystr),
                dataType: "json",
               	success: function (resp) {
                   	if(resp.code == 0){
                      	layer.msg('['+ datas.id +'] ' + field + '更改为:'+ value);
                   	}else{
                      	layer.msg('['+ datas.id +'] ' + field + '更改失败',{icon:2});
                   	}
              	}
          	});	
        },
        cancel: function(index, layero){ 
              layer.close(index);
        } 
        });        	
  	});
        /**
         * toolbar监听事件
         */
        table.on('toolbar(currentTableFilter)', function (obj) {
            if (obj.event === 'add') {  // 监听添加操作
                var index = layer.open({
                    title: '添加',
                    type: 2,
                    shade: 0.2,
                    maxmin:true,
                    shadeClose: true,
                    area: ['56%', '66%'],
                    content: '/page/xwaf/reqlimit_rule_add.html'+ location.search,
                    end: function(){
                    	window.parent.location.reload();//关闭open打开的页面时，刷新父页面
                    }
                });
                $(window).on("resize", function () {
                    layer.full(index);
                });
            } else if (obj.event === 'delete') {  // 监听删除操作
                var checkStatus = table.checkStatus('currentTableId')
                    , data = checkStatus.data;
                    layer.alert(JSON.stringify(data));
            }
        });

        table.on('tool(currentTableFilter)', function (obj) {
            var data = obj.data;
            if (obj.event === 'edit') { //暂时未用
                var index = layer.open({
                    title: '编辑',
                    type: 2,
                    shade: 0.2,
                    maxmin:true,
                    shadeClose: true,
                    area: ['45%', '70%'],
                    content: '/page/xwaf/reqlimit_customurl_rule_edit.html?limit_rule='+data.limit_rule,
                });
                $(window).on("resize", function () {
                    layer.full(index);
                });
                return false;
            } else if (obj.event === 'delete') {
                //console.log(data);
                layer.confirm('确定删除'+data.id+'?', {icon: 3, title:'删除提示',yes: function(index){
                     var index2 = layer.load(0, {shade: false});
                     layer.msg('请稍等...');
                			 $.ajax({
                			    url: "/xwaf/reqlimit/rule/Del?id="+data.id+"&appname="+data.appname,
                			    type: "get",
                			    success: function (resp) {
                            layer.close(index2);

                						 if(resp.code == 0){
                							 layer.msg('删除成功', {icon: 1});
                							 //window.location.reload();
                							 obj.del();
                						 }else{
                							 layer.msg(resp.msg,{icon:2});
                						 }
                				  }
                		   });		  	  
                },
            		  cancel: function(index, layero){ 
            			    layer.close(index);
                      layer.close(index2);
            			    console.log("不操作");
            		  } 
        		    });                
            }
        });
    });
</script>

</body>
</html>